/**
 * 
 */
package com.base.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.alibaba.fastjson.JSONObject;


/**
 * @author leiruiqi
 * 
 */
public class BaseController {

	protected final Log log = LogFactory.getLog(BaseController.class);

	/**
	 * @param bean
	 * @author leiruiqi
	 * @since
	 * 
	 */
	public void returnJsonObject(HttpServletResponse response,Object bean){
		String jsonStr = JSONObject.toJSONString(bean);
		returnMessage(response,jsonStr);
	}
	/**
     *
     * @param content
     */
	public void returnMessage(HttpServletResponse response,String content) {
		response.setCharacterEncoding("UTF-8");
		PrintWriter pWriter = null;
		try {
			pWriter = response.getWriter();
			pWriter.write(content);
		} catch (IOException e) {
			log.error("", e);
		} finally {
			if (pWriter != null) {
				pWriter.flush();
				pWriter.close();
			}
		}
	}
	
    
    @ModelAttribute
    public void initPath(HttpServletRequest request,HttpServletResponse response,ModelMap model){
    	String base = request.getContextPath();  
    	
		String fullPath = request.getScheme()+"://"+request.getServerName()+base; 
		model.addAttribute("base", base);
		model.addAttribute("fullPath", fullPath);
		
    }
    
    @InitBinder  
    protected void initBinder(WebDataBinder binder) throws ServletException {
  
          DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
          fmt.setLenient(false);

          CustomDateEditor dateEditor = new CustomDateEditor(fmt, true); 
          binder.registerCustomEditor(Date.class, dateEditor);  
          
          
          CustomCollectionEditor collectionEditor = new CustomCollectionEditor(List.class,true);
          
          binder.registerCustomEditor(List.class, collectionEditor);  
    }  
	
}
